package com.example.message.common;


import org.apache.commons.lang.StringUtils;

import java.util.Calendar;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by cyn on 16/5/15.
 */
public class StringUtil extends StringUtils {

    public final static Pattern pMakeTruthString = Pattern.compile("\\$\\!?\\{([^\\}]+)\\}");

    public final static String IP_FORMT_REG = "%03d";

    public final static String MANUNO_YEAR = "$!nian";

    public final static String MANUNO_MONTH = "$!yue";

    public final static String MANUNO_DAY = "$!ri";

    public static String createKey(String... key) {
        StringBuilder sb = new StringBuilder();
        for (String s : key) {
            sb.append(s).append("\t");
        }
        if (0 < sb.length()) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    public static String[] splitKey(String key){
        if(isNotBlank(key)){
            return key.split("\t");
        }
        return null;
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String formartSqlLike(String s) {
        if (isBlank(s)) {
            return null;
        }
        return "%" + sqlLikeDislodgeWildcards(s) + "%";
    }

    public static String formartSqlLikeRight(String s) {
        if (isBlank(s)) {
            return null;
        }
        return sqlLikeDislodgeWildcards(s) + "%";
    }

    public static String sqlLikeDislodgeWildcards(String str) {
        if (isBlank(str)) {
            str = "";
        } else {
            str = str.replace("[", "[[]");
            str = str.replace("%", "[%]");
            str = str.replace("_", "[_]");
            str = str.replace("^", "[^]");
            str = str.trim();
        }
        return str;
    }

    public static String convertWithhuanyuan(String ajaxString) {
        if (isBlank(ajaxString)) {
            ajaxString = "";
        } else {
            ajaxString = ajaxString.replaceAll("&quot;", "\"");
            ajaxString = ajaxString.replaceAll("&#039;", "'");
            ajaxString = ajaxString.replaceAll("&lt;", "<");
            ajaxString = ajaxString.replaceAll("&gt;", ">");
            ajaxString = ajaxString.replaceAll("&amp;", "&");
            ajaxString = ajaxString.replaceAll("&nbsp;", "");
            ajaxString = ajaxString.replaceAll("td width=\"187\"","td width=\"100%\"");
        }
        return ajaxString;
    }

    public static String ipFormat(String ip) {
        return ipFormat(ip.split("\\."));
    }


    public static String ipFormat(String[] ds) {
        StringBuilder sb = new StringBuilder(1);

        for (String d : ds) {
            sb.append(String.format(IP_FORMT_REG, Integer.parseInt(d)));
        }

        return sb.toString();
    }

    public static String ipFormat(String d1, String d2, String d3, String d4) {
        return "1" + String.format(IP_FORMT_REG, Integer.parseInt(d1))
                + String.format(IP_FORMT_REG, Integer.parseInt(d2))
                + String.format(IP_FORMT_REG, Integer.parseInt(d3))
                + String.format(IP_FORMT_REG, Integer.parseInt(d4));
    }


    /**
     * 稿号前缀解析
     */
    public static String decodeManuNo(String manuNo) {

        String newManuNo = manuNo;

        Calendar rightNow    =    Calendar.getInstance();

        if(manuNo.indexOf(MANUNO_YEAR)>-1){
            Integer year = rightNow.get(Calendar.YEAR);
            newManuNo =    newManuNo.replace(MANUNO_YEAR,String.valueOf(year));
        }

        if(manuNo.indexOf(MANUNO_MONTH)>-1){
            Integer month = rightNow.get(Calendar.MONTH)+1;
            newManuNo =    newManuNo.replace(MANUNO_MONTH,String.valueOf(month));

        }

        if(manuNo.indexOf(MANUNO_DAY)>-1){
            Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
            newManuNo =    newManuNo.replace(MANUNO_DAY,String.valueOf(day));

        }

        return newManuNo;

    }


    /**
     * 稿号初始化
     */
    public static String initManuNo(String manuNo, int rule_digit) {

        if ( rule_digit==0 ) {
            return manuNo;
        }

        for ( int i = 0; i < rule_digit-1; i++) {
            manuNo += "0";
        }

        return manuNo+"1" ;

    }


    /**
     * 更新稿号
     */
    public static String nextManuNo(String currentManuNo, int rule_digit) {

        StringBuilder manuNo = new StringBuilder("");

        String number = currentManuNo.substring(currentManuNo.length() - rule_digit, currentManuNo.length());

        manuNo.append(currentManuNo.substring(0,currentManuNo.length()- rule_digit));

        String nexuNumber = String.valueOf(Integer.valueOf(number)+1);

        //补0
        for (int i = 0; i <rule_digit-nexuNumber.length() ; i++) {

            manuNo.append("0");

        }

        return manuNo.append(nexuNumber).toString();
    }

    /**
     * 去除html代码中含有的标签
     * @param htmlStr
     * @return
     */
    public static String delHtmlTags(String htmlStr) {
        //定义script的正则表达式，去除js可以防止注入
        String scriptRegex = "<script[^>]*?>[\\s\\S]*?<\\/script>";
        // 定义style的正则表达式，去除style样式，防止css代码过多时只截取到css样式代码
        String styleRegex = "<style[^>]*?>[\\s\\S]*?<\\/style>";
        // 定义HTML标签的正则表达式，去除标签，只提取文字内容
        String htmlRegex = "<[^>]+>";
        // 定义空格,回车,换行符,制表符
        String spaceRegex = "\\s*|\t|\r|\n";
        // 过滤script标签
        htmlStr = htmlStr.replaceAll(scriptRegex, "");
        // 过滤style标签
        htmlStr = htmlStr.replaceAll(styleRegex, "");
        // 过滤html标签
        htmlStr = htmlStr.replaceAll(htmlRegex, "");
        // 过滤空格等
        htmlStr = htmlStr.replaceAll(spaceRegex, "");
        // 返回文本字符串
        return htmlStr.trim();


    }

    public static String doubleTrans(double d){
        if(Math.round(d)-d==0){
            return String.valueOf((long)d);
        }
        return String.valueOf(d);
    }

    /**
     * 下划线转驼峰法(默认小驼峰)
     *
     * @param line
     *            源字符串
     * @param smallCamel
     *            大小驼峰,是否为小驼峰(驼峰，第一个字符是大写还是小写)
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line, boolean ... smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        String regex = "([A-Za-z\\d]+)(_)?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(line);
        //匹配正则表达式
        while (matcher.find()) {
            String word = matcher.group();
            //当是true 或则是空的情况
            boolean scamel = smallCamel.length == 0 || smallCamel[0];
            if(scamel && matcher.start()==0){
                sb.append(Character.toLowerCase(word.charAt(0)));
            }else{
                sb.append(Character.toUpperCase(word.charAt(0)));
            }

            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    /**
     * 驼峰法转下划线
     *
     * @param line
     *            源字符串
     * @return 转换后的字符串  全部大写了
     */
    public static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase()
                .concat(line.substring(1));
        StringBuffer sb = new StringBuffer();
        String regex = "[A-Z]([a-z\\d]+)?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }

    /**
     * 驼峰法转下划线
     *
     * @param camelCaseName
     *            源字符串
     * @return 转换后的字符串
     */
    public static String underscoreName(String camelCaseName) {
        StringBuilder result = new StringBuilder();
        if (camelCaseName != null && camelCaseName.length() > 0) {
            result.append(camelCaseName.substring(0, 1).toLowerCase());
            for (int i = 1; i < camelCaseName.length(); i++) {
                char ch = camelCaseName.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append("_");
                    result.append(Character.toLowerCase(ch));
                } else {
                    result.append(ch);
                }
            }
        }
        return result.toString();
    }



    public static String makeTruthString(String source, Map<String, ?> values) {
        if (null == source && "".equals(source)) {
            return "";
        }

        Matcher m = pMakeTruthString.matcher(source);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String name = m.group(1);
            Object value = values.get(name);
            if (value == null) {
                value = "";
            }
            m.appendReplacement(sb, "");
            sb.append(value);
        }
        m.appendTail(sb);
        return sb.toString();
    }

}
